"use strict";

const Controller = require("egg").Controller;

class EmailController extends Controller {
  async index() {
    const { ctx, app } = this;

    const {
      current,
      size,
      addresser = "",
      recipients = "",
      theme = "",
    } = ctx.request.body;

    let sql = " ";

    if (addresser) {
      sql += `where addresser = "${addresser}" `;
    } else if (recipients) {
      sql += `where recipients = "${recipients}" `;
    } else if (theme) {
      sql += `where theme = "${theme}" `;
    }

    let limit = ` limit ${(current - 1) * size} , ${size}`;

    const data = await app.mysql.query(`select * from email ` + sql + limit);

    const total = (
      await app.mysql.query(`select count(*) as count from email` + sql)
    )[0].count;

    ctx.body = {
      code: 1,
      data,
      total,
    };
  }

  async del() {
    const { ctx, app } = this;

    const { id } = ctx.request.body;

    const multipleSelection = ctx.request.body;

    if (id) {
      await app.mysql.delete("email", { id });
    }

    if (multipleSelection.length) {
      multipleSelection.forEach(async (item) => {
        await app.mysql.delete("email", { id: item.id });
      });
    }

    ctx.body = {
      code: 1,
      msg: "删除成功",
    };
  }
}

module.exports = EmailController;
